const HOST = require('../../../config.js').host

let app = getApp()

Page({
    data: {
        windowType: 'cart',
        cartNum: 2,
        modalCartAnimation: '',
        modalBuyAnimation: '',
        hiddenModal: true,
        userId: 1,
        likeNum: 0,
        total: 0,

        desc: {
        }
    },

    makePhoneCall () {
        wx.makePhoneCall({
            phoneNumber: '0571-86822802'
        })
    },

    /**
     * 选择规格
     */
    selectCategory (e) {
        let total = parseFloat(this.data.desc.productPrice)
        let arr = this.data.desc.selectedCategory
        const specs = this.data.desc.productSpec
        const ds = e.currentTarget.dataset

        arr[ds.row] = ds.idx

        arr.forEach((selectedIdx, idx) => {
            total += parseFloat(specs[idx].productSpecItem[selectedIdx].itemPrice)
        })

        this.setData({
            'desc.total': total,
            'desc.selectedCategory': arr
        })
    },

    subAmount () {
        this.setData({
            'desc.amount': this.data.desc.amount === 1 ? 1 : this.data.desc.amount - 1
        })
    },

    addAmount () {
        this.setData({
            'desc.amount': this.data.desc.amount + 1
        })
    },

    navigateToStore () {
        wx.navigateTo({
          url: '../store/store?id=' + this.data.desc.id
        })
    },

    navToHome () {
        wx.switchTab({
          url: '../../home/home'
        })
    },

    /**
     * 点击收藏触发事件
     */
    like () {
        let isLike = this.data.desc.isLike

        if (isLike) {
            this.cancelLike(this.data.productId)
        } else {
            this.uploadLike(this.data.productId)
        }

        this.setData({
            'desc.isLike': isLike ? 0 : 1
        })
    },

    showWindow (e) {
        let type = e.currentTarget.dataset.type
        let windowType

        if (type === 'cart') {
            windowType = 'cart'
        } else [
            windowType = 'buy'
        ]

        let animation = wx.createAnimation({
            duration: 250,
            timingFunction: 'ease-out', // "linear","ease","ease-in","ease-in-out","ease-out","step-start","step-end"
            delay: 0,
            transformOrigin: '50% 50% 0',
        })
        animation.bottom(0).step()
        this.setData({
            windowType,
            hiddenModal: false,
            animation: animation.export()
        })
    },

    hiddenWindow (event) {
        let animation = wx.createAnimation({
            duration: 250,
            timingFunction: 'ease-out', // "linear","ease","ease-in","ease-in-out","ease-out","step-start","step-end"
            delay: 0,
            transformOrigin: '50% 50% 0',
        })
        animation.bottom(-500).step()

        this.setData({
            hiddenModal: true,
            animation: animation.export()
        })

        if (event.currentTarget.dataset.type !== 'modal') {
            this.addToCart()
        }

        if (event.currentTarget.dataset.type === 'buy') {
            this.generateOrder()

            wx.navigateTo({
                url: '../../settlement/list/list?total=' + (this.data.desc.total * this.data.desc.amount)
            })
        }
    },

    /**
     * 添加到购物车中
     */
    addToCart () {
        // 对添加的商品进行检查，是否选择了规格
        // let selectAll = true
        // this.data.desc.productSpec.forEach((v, idx) => {
        //     if (this.data.desc.selectedCategory === undefined || this.data.desc.selectedCategory[idx] === undefined) {
        //         wx.showToast({
        //             title: '请选择' + v.specName,
        //             icon: 'success',
        //             duration: 1000
        //         })

        //         selectAll = false
        //     }
        // })

        // if (!selectAll) {
        //     return
        // }

        let cart = []
        try {
            let value = wx.getStorageSync('cart')

            if (value) {
                let rst = this.checkCart(value)

                if (!rst.isDiffAll) {
                    cart = rst.cart
                } else {
                    cart = cart.concat(value)
                    cart.push(this.data.desc)
                }
            } else {
                cart.push(this.data.desc)
            }
        } catch (e) {
            console.error(e)
        }
        console.log(cart)
        let self = this
        wx.setStorage({
            key: 'cart',
            data: cart,
            success: function(res){
                self.getCart()
                wx.showToast({
                    title: '添加购物车成功',
                    duration: 1000,
                    icon: 'success'
                })
            }
        })
        
    },

    checkCart (cart) {
        let isDiffAll = true

        cart.forEach(v => {
            let isSame
            if (v.id === this.data.desc.id) {
                isSame = v.selectedCategory.every((cate, idx) => {
                    return cate == this.data.desc.selectedCategory[idx]
                })

                if (isSame) {
                    isDiffAll = false
                    v.amount += this.data.desc.amount
                }
            }
        })

        return {
            isDiffAll,
            cart
        }
    },

    generateOrder () {
        app.globalData.order.goods = [this.data.desc]
    },

    /** 服务端通讯 **/

    checkLike (id) {
        wx.request({
          url: HOST + 'v1/userFavorite/getFavorite/' + app.userId + '/' + id,
          method: 'GET', 
          // header: {}, 
          success: function(res){
            if (res.data.sysCode === 1) {
                this.setData({
                    'desc.isLike': res.data.data
                })
            }
          }.bind(this)
        })
    },

    uploadLike (id) {
        wx.request({
            url: HOST + 'v1/userFavorite',
            data: {
                userId: app.userId,
                productId: id
            },
            method: 'POST',
            success: function(res){
                if (res.data.sysCode === 1) {
                    this.getLikeNum(id)                    
                    console.log('喜欢商品成功！')
                }
            }.bind(this)
        })
    },

    cancelLike (id) {
        wx.request({
            url: HOST + 'v1/userFavorite',
            data: {
                userId: app.userId,
                productId: id
            },
            method: 'DELETE',
            success: function(res){
                if (res.data.sysCode === 1) {
                    this.getLikeNum(id)                    
                    console.log('喜欢商品成功！')
                }
            }.bind(this)
        })
    },

    getLikeNum (id) {
        let self = this
        wx.request({
            url: HOST + 'v1/userFavorite/getFavoriteNum/' + id,
            method: 'GET', 
            success: function (res) {
                if (res.data.sysCode === 1) {
                    self.setData({
                        likeNum: res.data.data
                    })
                }
            }
        })
    },

    getDetail (id) {
        wx.request({
          url: HOST + 'v1/product/info/' + id,
          method: 'GET', 
          success: function(res){
            if (res.data.sysCode === 1) {
                let detail = res.data.data
                detail.total = parseFloat(detail.productPrice)
                detail.amount = 1
                detail.selectedCategory = []
                for (let i = 0; i < detail.productSpec.length; i++) {
                    detail.selectedCategory.push(0)
                }
                detail.productSpec.forEach(spec => {
                    detail.total += parseFloat(spec.productSpecItem[0].itemPrice)
                })

                this.checkLike(detail.id)
                this.getLikeNum(detail.id)
                this.setData({
                    desc: detail
                })
            }
          }.bind(this)
        })
    },

    getCart () {
        this.setData({
            cartNum: wx.getStorageSync('cart').length
        })
    },

    /** 生命周期 **/

    onLoad (options) {
        this.getDetail(options.id)
        this.setData({
            productId: options.id
        })

        // 带参数二维码参数
        app.globalData.qrcode = Object.assign({}, app.globalData.qrcode, options)

    },

    onShow () {
        this.getCart()
    }
})